<template>
	<view class="container">
		<view class="reading-content" :style="{'background-color':bgColor}">

			<yingbing-text-reader ref="page" :page-type="pageType" :total-chapter="readBookInfo.chapterList.length"
				preloadable back-show enableClick :font-size="fontsize" :fontFamily="fontFace.fontFamily"
				:line-height="lineHeight" :color="color" :background="bgColor" :slide="slide" :split="split"
				:topGap="deviceInfoRes.statusBarHeight" @loadmore="loadmoreContent" :clickOption="clickOption"
				@single-click="clickToMenu" @change="currentChange">
			</yingbing-text-reader>

		</view>

		<view v-show="hidenNavOrBottomState" class="menu-overlay">
			<uni-transition :duration="200" :mode-class="modeClass1" :styles="transfromClass1" :show="transShow1">
				<view class="menu-overlay-bg"
					:style="{'backgroundColor':mainReadBackStyles[sqlMainBackIndex].maskBg}">
					<view
						class="header-bar"
						:style="{'backgroundColor':mainReadBackStyles[sqlMainBackIndex].maskBg,'top':statusBarHeight+'px'}">
						<view
							class="back-button"
							@click="backToView">
							<image class="back-icon"
								src="../../../static/readDetail/backToViewIcon.png"></image>
						</view>
						<view class="chapter-title-container">
							<label
								class="chapter-title"
								:style="{color:color}">{{getChapterName()}}</label>
						</view>
					</view>

				</view>
			</uni-transition>

			<view class="menu-close-overlay" @tap="hidenNavOrBottomTools">
			</view>

			<uni-transition :duration="200" :mode-class="modeClass2" :styles="transfromClass2" :show="transShow2">

				<view class="settings-panel"
					:style="{'backgroundColor':mainReadBackStyles[sqlMainBackIndex].maskBg}">
					<!-- 调整字间距和大小 -->
					<view class="font-settings-row" >
						<view class="setting-group" style="margin-left: 10px;">
							<view class="setting-label-container">
								<label
									class="setting-label">{{ $t('readDetail.font') }}</label>
							</view>
							<view
								class="slider-container">
								<u-slider min="10" max="30" v-model="fontSlidValue" class="setting-slider"
									block-color="rgb(138, 109, 233)" inactive-color="rgb(0, 0, 0)"
									:block-style="{width:'100%'}" @change="sqlFontSizeClick($event,'fontSize')">
								</u-slider>
							</view>
						</view>
						<view class="setting-group">
							<view class="setting-label-container">
								<label
									class="setting-label">{{ $t('readDetail.spacing') }}</label>
							</view>
							<view
								class="slider-container">
								<u-slider min="10" max="50" v-model="spaceBetWordsValues" class="setting-slider"
									block-color="rgb(138, 109, 233)" inactive-color="rgb(0, 0, 0)"
									:block-style="{width:'200px'}" @change="sqlFontSizeClick($event,'lineHeight')">
								</u-slider>
							</view>
						</view>

					</view>

					<!-- 阅读动画方式类型 -->
					<view class="animation-type-row" style="margin-top: 8px;">

						<view class="animation-type-label-container">
							<label
								class="setting-label">{{ $t('readDetail.readingAnimation') }}</label>
						</view>
						<view class="animation-type-options" style="overflow-x: scroll;"> 
							<view v-for="(item,index) in switchTypeInfo" @click="enterReadTypeClick(index)" style="margin-right: 15px;">
								<view v-if="item.sqlState == true"
									class="animation-type-option animation-type-option-active">
									<view class="animation-type-text">{{ $t('readDetail.' + item.typeKey) }}</view>
								</view>
								<view v-if="item.sqlState == false"
									class="animation-type-option animation-type-option-inactive">
									<view class="animation-type-text animation-type-text-inactive">{{ $t('readDetail.' + item.typeKey) }}</view>
								</view>
							</view>
						</view>

					</view>

					<!-- 阅读背景样式 -->
					<view
						class="background-options-row">

						<view v-for="(item,index) in readBackStyles" @click="mainReadBackClick(index)">

							<view class="background-option" :style="item">
							</view>

						</view>

					</view>

					<view class="navigation-buttons-row" style="margin-top: 10px;">

						<custom-button class="nav-button" :text="$t('readDetail.prevChapter')" icon="arrow-left" textColor="#000"
							@click="goCurrent('before')"></custom-button>
						<custom-button class="nav-button" style="margin-left: 10px;" :text="$t('readDetail.catalog')" icon="list" textColor="#000"
							@click="enterANovelDirClick"></custom-button>
						<custom-button class="nav-button" style="margin-left: 10px;" :text="$t('readDetail.nextChapter')" icon="arrow-right"
							iconPosition="right" textColor="#000" @click="goCurrent('next')"></custom-button>
					</view>
				</view>
			</uni-transition>
		</view>



	</view>
</template>

<script>
	import {
		nextTick
	} from "vue"
	import data from "./data.js"
	import methods from "./methods.js"
	import CustomButton from "../../../components/custom-button/CustomButton.vue"
	export default {
		components: {
			CustomButton
		},
		data() {
			return data.init(this)
		},
		onReady() {

			//获取章节内容
			this.getChaptersInfo()

		},
		onLoad(options) {
			var that = this;
			this.bookInfo = JSON.parse(options.bookInfo);
			this.readBookInfo.bookId = String(this.bookInfo.bookCode);
			this.$sqlDBConfig.insertBookReadData([this.bookInfo]);
			uni.$on('switchSection', async (data) => {
				//获取之前看的记录
				let dataInfos = uni.getStorageSync(that.readBookInfo.bookId)
				that.changeChapterMethod(dataInfos)
			})
		},
		onShow() {

		},
		//如果不加这句，会导致跳转到别的页面后也是全屏
		onHide() {

		},
		created() {


			this.deviceInfoRes = uni.getSystemInfoSync();
			// 设置导航栏的高度
			this.navViewHeight = this.deviceInfoRes.statusBarHeight + 44;
			this.statusBarHeight = this.deviceInfoRes.statusBarHeight;
			this.safeAreaHeight = this.deviceInfoRes.screenHeight - this.deviceInfoRes.safeArea.bottom + 156;
			this.bottomSafeAreaHeight = this.deviceInfoRes.screenHeight - this.deviceInfoRes.safeArea.bottom;
			this.initPageStyleView();


		},

		mounted() {



		},
		methods: {

			//存档当前章节
			setStorageSync(param) {
				let obj = {
					bookId: this.readBookInfo.bookId,
					readProcessData: param
				}
				//存储下当前看到当前小说的哪个章节
				uni.setStorageSync("readProcessData" + this.bookInfo.bookCode, obj)
			},


			//  初始化页面样式
			initPageStyleView() {

				var readSetInfoStr = uni.getStorageSync("readDetailSetInfo");
				if (readSetInfoStr.length > 0) {

					var readSetInfo = JSON.parse(readSetInfoStr)
					this.bgColor = readSetInfo.bgColor;
					this.color = readSetInfo.color;
					this.switchTypeItem = this.switchTypeInfo[readSetInfo.sqlMainBackIndex];
					this.pageType = readSetInfo.pageType;
					this.enablePreload = readSetInfo.enablePreload;
					this.fontsize = readSetInfo.fontsize;
					this.lineHeight = readSetInfo.lineHeight;
					this.slide = readSetInfo.slide;
					this.sqlMainBackIndex = readSetInfo.sqlMainBackIndex;
					this.fontSlidValue = readSetInfo.fontSlidValue;
					this.spaceBetWordsValues = readSetInfo.spaceBetWordsValues;

					this.switchTypeInfo.forEach((item) => {
						if (item.pageType == this.pageType) {
							item.sqlState = true;
						} else {
							item.sqlState = false;
						}
					})

					this.mainReadBackClick(this.sqlMainBackIndex);

				} else {
					
					this.mainReadBackClick(3);
					this.switchTypeItem = this.switchTypeInfo[1];
					this.pageType = this.switchTypeItem.pageType
					this.saveReadSetMethod();

				}



			},

			//  读数开始方法
			//  获取章节内容
			async getChaptersInfo() {

				var that = this;
				//获取之前看的记录
				that.readBookInfo.seeBook = uni.getStorageSync(that.readBookInfo.bookId) || {
					bookId: that.readBookInfo.bookId,
					chapter: 1,
					start: 0
				}
				var bookId = that.readBookInfo.bookId;
				try {
					var res = await that.$api.chapterList(bookId);
					if (res.statusCode == 200) {
						//  获取章节列表
						that.readBookInfo.chapterList = res.data.data;
						//  初始化第一章节内容
						that.initPage()
					}

				} catch (error) {

				}

			},
			// 初始化加载第一章节
			//初始化页面传入内容和当前章节
			async initPage() {
				let that = this;
				const {
					page
				} = this.$refs;
				let readInfo = uni.getStorageSync("readProcessData" + this.bookInfo.bookCode)
				if (readInfo == null || readInfo == "") {
					let chapterItem = await that.getChapter(1);
					const chapters = [chapterItem];
					setTimeout(() => {
						page.init({
							chapters: chapters,
							title: that.bookInfo.bookName,
							current: 1,
							start: 0
						})
					}, 100)
				} else {
					let chapterItem = await that.getChapter(readInfo.readProcessData.detail.index);
					const chapters = [];
					setTimeout(async () => {
						
						
						if (readInfo.readProcessData.detail.index - 1 < 1) {
							chapters.push(chapterItem)
						} else {
							let chapterItem1 = await that.getChapter(readInfo.readProcessData.detail.index - 1);
							chapters.push(chapterItem)
							chapters.push(chapterItem1)
						}
						if (readInfo.readProcessData.detail.index + 1 > that.readBookInfo.chapterList.length) {
						
						} else {
							let chapterItem2 = await that.getChapter(readInfo.readProcessData.detail.index + 1);
							chapters.push(chapterItem2)
						}
						
						page.init({
							chapters: chapters,
							title: that.bookInfo.bookName,
							current: readInfo.readProcessData.detail.index,
							start: readInfo.readProcessData.detail.start
						})
					}, 100)
				}

			},

			async loadmoreContent(current, callback) {
				let that = this;
				let chapterItem = await that.getChapter(current)
				callback('success', chapterItem);
			},


			// 获取章节详情
			async getChapter(index) {

				let that = this;
				var content = await that.requsetText(that.readBookInfo.chapterList[index - 1].cId, that.readBookInfo
					.chapterList[index - 1]);
				that.chapterInfo = that.readBookInfo.chapterList[index - 1];
				return {
					title: that.readBookInfo.chapterList[index - 1].cName,
					content: content,
					index: index,
					isStart: index == 1,
					isEnd: index == that.readBookInfo.chapterList.length
				}

			},

			// 获取小说内容
			requsetText(cId, chapterName) {

				var that = this;
				return new Promise((resolve, reject) => {
					var readInfo = {
						bookCode: that.readBookInfo.bookId,
						chapterCode: cId,
					}
					that.$api.chapterDetail(readInfo).then(res => {
						res.data.data = res.data.data.replace(/[\'\"\\\/\b\f\n\t]/g, '');
						if (res.statusCode == 200) {
							let exp = new RegExp('&nbsp;', 'g')
							let exp2 = new RegExp('<br>', 'g')
							var dataStr = ""
							if (res.data.data.length < 1) {
								var str = this.$t('readDetail.chapterEmpty')
								dataStr = str.replace(exp, '').replace(exp2, '')
							} else {
								dataStr = res.data.data.replace(exp, '').replace(exp2, '')
							}
							dataStr = dataStr;

							resolve(dataStr)
						} else {
							resolve(' ')
						}
					}).catch(error => {
						resolve(' ')
					})
				})

			},

			// 切换章节核心代码
			async changeChapterMethod(dataInfos) {
				let that = this
				const {
					page
				} = that.$refs;
				// 初始化章节内容，重第一章节开始
				let chapterItem = await that.getChapter(dataInfos.chapter);
				let chapterItemBefore = {}
				let chapters = []
				if (dataInfos.chapter - 1 < 1) {
					chapters.push(chapterItem)
				} else {
					let chapterItem1 = await that.getChapter(dataInfos.chapter - 1);
					chapters.push(chapterItem)
					chapters.push(chapterItem1)
				}
				if (dataInfos.chapter + 1 > that.readBookInfo.chapterList.length) {

				} else {
					let chapterItem2 = await that.getChapter(dataInfos.chapter + 1);
					chapters.push(chapterItem2)
				}


				setTimeout(() => {
					page.change({
						chapters: chapters,
						current: dataInfos.chapter,
						start: 1
					}) //传入章节列表，避免触发loadmore，也可以通过该方式更新章节内容
				}, 100)

			},
			//  -----------------------------  阅读模块核心代码
			clickToMenu(e) {

				this.mainClickState = true
				this.hidenNavOrBottomState = true;

				if (this.transShow1 == false) {
					this.transfromClass1.height = this.navViewHeight + "px";
					this.transShow1 = true;
				} else {
					this.transShow1 = false;
				}

				if (this.transShow2 == false) {
					this.transfromClass2.height = this.safeAreaHeight + "px";
					this.transShow2 = true;
				} else {
					this.transShow2 = false;
				}


			},
			currentChange(e) {

				
				this.readBookInfo.current = parseInt(e.detail.index)
				this.chapterInfo = this.readBookInfo.chapterList[e.detail.index - 1];
				this.chapterInfo.readProcess = e;
				this.setChapterInfo.cName = this.chapterInfo.readProcess.detail.title;
				//存档当前章节
				this.setStorageSync(e)

			},
			getChapterName() {
				let that = this;
				return that.setChapterInfo.cName
			},


			//  -----------------------------  阅读模块核心代码  结束
			backToView() {

				uni.navigateBack({

				});

			},
			hidenNavOrBottomTools() {

				if (this.mainClickState == true) {
					this.transShow2 = false;
					this.transShow1 = false;
					setTimeout(() => {
						this.hidenNavOrBottomState = false;
					}, 300)
				} else {
					this.mainClickState = false;
				}

			},

			//  配置页面切换的类型
			enterReadTypeClick(index) {

				for (var i = 0; i < this.switchTypeInfo.length; i++) {
					var dataItem = this.switchTypeInfo[i];
					if (i == index) {
						dataItem.sqlState = true;
					} else {
						dataItem.sqlState = false;
					}
				}

				this.switchTypeItem = this.switchTypeInfo[index];
				this.pageType = this.switchTypeItem.pageType
				this.saveReadSetMethod();

			},

			//  设置阅读样式
			mainReadBackClick(index) {
				for (var i = 0; i < this.readBackStyles.length; i++) {

					var dataItem = this.readBackStyles[i];
					if (i == index) {
						dataItem.border = '1px solid #6d583b';
					} else {
						dataItem.border = '0px solid #6d583b';
					}

				}

				this.sqlMainBackIndex = index;
				this.bgColor = this.mainReadBackStyles[index].background;
				this.color = this.mainReadBackStyles[index].fontColor;
				this.saveReadSetMethod();

			},

			//  设置字体颜色
			sqlFontSizeClick(e, type) {

				if (type == "fontSize") {
					this.fontsize = e;
					this.fontSlidValue = this.fontsize;
				} else if (type == "lineHeight") {
					this.lineHeight = e;
					this.spaceBetWordsValues = this.lineHeight;
				}
				this.saveReadSetMethod();

			},

			//  进入目录列表
			enterANovelDirClick() {

				uni.navigateTo({
					url: './aNovelDirectory/aNovelDirectoryView?bookCode=' + this.bookInfo.bookCode +
						"&chapterIndex=" + this.chapterInfo.readProcess.detail.index + "&pageType=readDetail"
				})

			},

			//  获取阅读详情
			async getReadingDetailsData(cId, bookCode) {

				var that = this
				var readInfo = {
					bookCode: bookCode,
					chapterCode: cId,
				}

				try {
					var res = await this.$api.chapterDetail(readInfo);
					if (res.statusCode == 200) {
						var chapterDetail = res.data.data;
						return chapterDetail;
					} else {
						return "获取失败";
					}

				} catch (error) {
					return "";
				}

			},
			//切换章节
			async goCurrent(text) {

				let that = this;
				let readInfo = uni.getStorageSync("readProcessData" + this.bookInfo.bookCode)
				let yuLoadIndex = 0;
				if (text == 'next') {
					yuLoadIndex = readInfo.readProcessData.detail.index + 1
					if (yuLoadIndex >= that.readBookInfo.chapterList.length) {
						uni.showToast({
							title: that.$t('readDetail.lastChapter'),
							icon: 'none'
						});
						return
					}
				} else if (text == 'before') {
					yuLoadIndex = readInfo.readProcessData.detail.index - 1
					if (yuLoadIndex <= 1) {
						uni.showToast({
							title: that.$t('readDetail.noPrevChapter'),
							icon: 'none'
						});
						return
					}
				}
				const {
					page
				} = that.$refs;
				// 初始化章节内容，重第一章节开始
				let chapterItem = await that.getChapter(yuLoadIndex);
				const chapters = [chapterItem];
				setTimeout(() => {
					page.change({
						chapters: chapters,
						current: yuLoadIndex,
						start: 0
					}) //传入章节列表，避免触发loadmore，也可以通过该方式更新章节内容
				}, 100)

			},

			//  默认数据配置
			saveReadSetMethod() {
				this.readSetInfo = {};

				//  是否预加载数据
				this.readSetInfo.enablePreload = this.enablePreload;

				//  页面翻页类型（real、none）
				this.readSetInfo.pageType = this.pageType;

				//  页面字体大小
				this.readSetInfo.fontsize = this.fontsize;

				//  行间距
				this.readSetInfo.lineHeight = this.lineHeight;

				//  字体颜色
				this.readSetInfo.color = this.color;

				//  页面背景颜色
				this.readSetInfo.bgColor = this.bgColor;

				//  页面左右编辑
				this.readSetInfo.slide = this.slide;

				// 获取页面主题背景颜色数据
				this.readSetInfo.sqlMainBackIndex = this.sqlMainBackIndex;

				// 获取字体间距
				this.readSetInfo.fontSlidValue = this.fontSlidValue;
				this.readSetInfo.spaceBetWordsValues = this.spaceBetWordsValues;

				// 获取页面主题背景颜色数据
				this.readSetInfo.sqlMainBackIndex = this.sqlMainBackIndex;

				var readSetInfoStr = JSON.stringify(this.readSetInfo);
				uni.setStorageSync("readDetailSetInfo", readSetInfoStr)

			}







		}
	}
</script>

<style scoped lang="scss">
	.container {
		position: absolute;
		width: 100vw;
		height: 100vh;
	}

	.reading-content {
		position: absolute;
		width: 100%;
		height: 100vh;
	}

	.menu-overlay {
		position: absolute;
		width: 100vw;
		height: 100vh;
	}

	.menu-overlay-bg {
		width: 100%;
		height: 100%;
	}

	.header-bar {
		position: absolute;
		width: 100%;
		display: flex;
		align-items: center;
		flex-direction: row;
		height: 44px;
	}

	.back-button {
		height: 100%;
		width: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-icon {
		height: 25px;
		width: 25px;
	}

	.chapter-title-container {
		height: calc(100% - 66px);
		width: 200px;
		display: flex;
		align-items: center;
	}

	.chapter-title {
		font-size: 15px;
		font-family: PingFang SC,"Helvetica Neue",Helvetica,STHeiTi,sans-serif;
		margin-left: 0px;
	}

	.menu-close-overlay {
		position: absolute;
		height: 100%;
		width: 100%;
		z-index: 99999;
	}

	.settings-panel {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.font-settings-row {
		width: 100%;
		height: auto;
		display: flex;
		flex-direction: row;
	}

	.setting-group {
		width: 100%;
		height: auto;
		display: flex;
		align-items: center;
	}

	.setting-label-container {
		display: flex;
		align-items: center;
		margin-right: 10px;
	}

	.setting-label {
		font-family: PingFang SC,"Helvetica Neue",Helvetica,STHeiTi,sans-serif;
		font-size: 12px;
		color: rgb(103, 73, 35);
		white-space: nowrap;
		margin-left: 10px;
	}

	.animation-type-text {
		font-size: 12px !important;
		color: #fff;
	}

	.animation-type-text-inactive {
		color: #007aff;
	}

	.slider-container {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.setting-slider {
		width: 100%;
	}

	.animation-type-row {
		width: 100%;
		height: auto;
		display: flex;
		flex-direction: row;
	}

	.animation-type-label-container {
		margin-bottom: 0px;
	}

	.animation-type-options {
		display: flex;
		align-items: center;
		flex-direction: row;
	}

	.animation-type-option {
		min-width: 42px;
		height: 26px;
		padding: 0 5px;
		border-radius: 3px;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 10px;
	}

	.animation-type-option-active {
		background-color: #007aff;
		border: 0px solid #007aff;
	}

	.animation-type-option-inactive {
		background-color: #ffffff;
		border: 0px solid #007aff;
	}

	.animation-type-text {
		font-size: 12px !important;
		color: #fff;
		white-space: nowrap;
	}

	.animation-type-text-inactive {
		color: #007aff;
	}

	.background-options-row {
		width: 100%;
		height: 46px;
		margin-top: 8px;
		padding: 0 0px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.background-option {
		height: 26px;
		width: 26px;
		border-radius: 50%;
	}

	.navigation-buttons-row {
		width: calc(100% - 30px);
		margin-left: 15px;
		display: flex;
		justify-content: space-between;
	}

	.nav-button {
		height: 30px;
		flex: 1;
		margin: 0 5px;
	}

	::v-deep(.u-button__text) {
		font-size: 12px !important;
		color: rgb(82, 77, 81) !important;
	}

	::v-deep(.u-button--primary) {
		color: #fff;
		background-color: #3c9cff;
		border-color: #3c9cff;
		border-width: 0px;
		border-style: solid;
		border-radius: 0px;
	}
</style>